package com.wz.wx;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;

/**微信小程序解码
 * @author wangze
 * @date 2018-05-08 16:59.
 **/
public class WXCore {
    public static void main(String[] args) throws Exception{
        String appId = "wx4f4bc4dec97d474b";
        String encryptedData = "i4X2qoe5eowQMhNitQjCJ8NP+jtLPSX0jAgO5yExho/kn+dWun8FkHDDwldAnuXljYCCKzatfF3mYuxlfk1vdbpDmgrHDHg1hGQzm4jG4aZ4ueBeXWKiw9+s31y8k3hxS2Td9aqUUdHYPgeMZ0Y6OhSCf3kuxQSRBjeJhXLrqKUv1VAv+lrbyobdOXE7pPgKp0ODLPMHJlMxxVsLEhdF7w==";
        String sessionKey = "uvTG3Him51CStIZYX+0EQg==";
        String iv = "T5VL3nwnO+zxPXXNk2aDDw==";
        System.out.println(wxDecrypt(encryptedData, sessionKey,iv));
    }

    public static String wxDecrypt(String encryptedData, String sessionKey, String iv){
        String result = "";
        try {
            AES aes = new AES();
            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if(null != resultByte && resultByte.length > 0){
                result= new String(WxPKCS7Encoder.decode(resultByte));
            }
        } catch (Exception e) {
            result = "";
            e.printStackTrace();
        }
        return result;
    }

}
